package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.view.View
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.PlatesDetailInfo
import com.lancoo.znbkxx.teacher.utils.FormatUtil
import com.lancoo.znbkxx.teacher.utils.HtmlUtils
import kotlinx.android.synthetic.main.fragment_plates_detail.*
import kotlinx.android.synthetic.main.item_achievement_markview.view.*
import java.math.BigDecimal

/**
 * @author : Admin
 * @date   : 2020/12/18
 * @desc   :
 */
class SelfPlatesFragment : BaseFragment() {
    private val excellent = mutableListOf<Entry>()
    private val personal = mutableListOf<Entry>()
    private val excellent2nd = mutableListOf<Entry>()
    private val personal2nd = mutableListOf<Entry>()
    private val excellent3rd = mutableListOf<Entry>()
    private val personal3rd = mutableListOf<Entry>()
    private val type by lazy { arguments?.getInt("type") }
    private lateinit var dataSetExcellent: LineDataSet
    private lateinit var dataSetExcellent2nd: LineDataSet
    private lateinit var dataSetExcellent3rd: LineDataSet
    private lateinit var lineChartData: LineData
    private val platesDetail by lazy { arguments?.getParcelable<PlatesDetailInfo>("plates") }
    override fun createLayout(): Int {
        return R.layout.fragment_plates_detail
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    override fun initView(view: View?) {
        if (type == 0) {
            iv_bg.setImageResource(R.mipmap.aibk_icon_plate_bg)
        } else {
            iv_bg.setImageResource(R.mipmap.aibk_icon_plate_bg2)
        }
        platesDetail?.let {
            initHint(it)
            initPlates(lc_listen, it)
        }
        tv_excellent.setOnClickListener {
            if (tv_excellent.tag == 0) {
                tv_excellent.tag = 1
                tv_excellent.setCompoundDrawablesWithIntrinsicBounds(
                        resources.getDrawable(R.mipmap.aibk_icon_plate4, null), null, null, null)
                lineChartData.addDataSet(dataSetExcellent)
                lineChartData.addDataSet(dataSetExcellent2nd)
                lineChartData.addDataSet(dataSetExcellent3rd)
            } else {
                tv_excellent.tag = 0
                tv_excellent.setCompoundDrawablesWithIntrinsicBounds(
                        resources.getDrawable(R.mipmap.aibk_icon_plate6, null), null, null, null)
                lineChartData.removeDataSet(dataSetExcellent)
                lineChartData.removeDataSet(dataSetExcellent2nd)
                lineChartData.removeDataSet(dataSetExcellent3rd)
            }
            lc_listen.notifyDataSetChanged()
            lc_listen.invalidate()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initHint(data: PlatesDetailInfo) {
        val first = data.CognitiveList.FirstList.size
        val second = data.CognitiveList.SecondList.size
        val third = data.CognitiveList.ThirdList.size
        val totalReviewed = data.CognitiveList.FirstList.size + data.CognitiveList.SecondList.size + data.CognitiveList.ThirdList.size
        val firstPercent = if (totalReviewed == 0) "0" else FormatUtil.div(first * 100.toDouble(),
                totalReviewed.toDouble(), 0)
                .stripTrailingZeros().toPlainString()
        val secondPercent = if (totalReviewed == 0) "0" else FormatUtil.div(second * 100.toDouble(),
                totalReviewed.toDouble(), 0)
                .stripTrailingZeros().toPlainString()
        val thirdPercent = 100 - firstPercent.toInt() - secondPercent.toInt()
        tv_title.text = if (type == 0) "听说认知图谱" else "读写认知图谱"
        tv_total_score.text = HtmlUtils.setText(
                "${if (type == 0) "听说认知积分" else "读写认知积分"}：<font color='#00afff'>${data.Score}</font>")
        tv_last_week.text = HtmlUtils.setText(
                "较上周：<font color='#ff9900'>${if (data.WeakUp > 0) "${data.WeakUp}↑" else if (data.WeakUp < 0) "${data.WeakUp}↓" else "无变化"}</font>")
        tv_total_percent.text = HtmlUtils.setText(
                "总体优秀率：<font color='#00c0a2'>${data.GreatRate}%</font>")
        //        tv_reviewed.text = HtmlUtils.setText("已复习知识点<font color='#ff9900'>${totalReviewed}个</font>")
        tv_first_child.text = HtmlUtils.setText(
                "<font color='#2dbcff'>${data.CognitiveList.FirstList.size}个 (${firstPercent}%)")
        tv_second_child.text = HtmlUtils.setText(
                "<font color='#ffc49d'>${data.CognitiveList.SecondList.size}个 (${secondPercent}%)")
        tv_third_child.text = HtmlUtils.setText(
                "<font color='#ff8888'>${data.CognitiveList.ThirdList.size}个 (${thirdPercent}%)")
        tv_unreviewed.text = HtmlUtils.setText(
                "上图仅显示已复习知识点，剩余未复习知识点${data.UnstudyCognitiveCount}个未展示")
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private fun initPlates(lineChart: LineChart, data: PlatesDetailInfo) {
        data.CognitiveList.FirstList.forEachIndexed { index, first ->
            val entryExcellent = Entry(index.toFloat(), first.ExcellentScore.toFloat())
            val entryPersonal = Entry(index.toFloat(), first.PersonalScore.toFloat())
            excellent.add(entryExcellent)
            personal.add(entryPersonal)
        }
        data.CognitiveList.SecondList.forEachIndexed { index, first ->
            val entryExcellent = Entry(index.toFloat() + data.CognitiveList.FirstList.size,
                    first.ExcellentScore.toFloat())
            val entryPersonal = Entry(index.toFloat() + data.CognitiveList.FirstList.size,
                    first.PersonalScore.toFloat())
            excellent2nd.add(entryExcellent)
            personal2nd.add(entryPersonal)
        }
        data.CognitiveList.ThirdList.forEachIndexed { index, first ->
            val entryExcellent = Entry(
                    index.toFloat() + data.CognitiveList.FirstList.size + data.CognitiveList.SecondList.size,
                    first.ExcellentScore.toFloat())
            val entryPersonal = Entry(
                    index.toFloat() + data.CognitiveList.FirstList.size + data.CognitiveList.SecondList.size,
                    first.PersonalScore.toFloat())
            excellent3rd.add(entryExcellent)
            personal3rd.add(entryPersonal)
        }
        lineChart.apply {
            dataSetExcellent = LineDataSet(excellent, "excellent")
            dataSetExcellent.apply {
                color = Color.parseColor("#22d7bb")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            dataSetExcellent2nd = LineDataSet(excellent2nd, "excellent")
            dataSetExcellent2nd.apply {
                color = Color.parseColor("#22d7bb")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            dataSetExcellent3rd = LineDataSet(excellent3rd, "excellent")
            dataSetExcellent3rd.apply {
                color = Color.parseColor("#22d7bb")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            val dataSetPersonal = LineDataSet(personal, "personal")
            dataSetPersonal.apply {
                color = Color.parseColor("#2dbcff")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                setDrawFilled(true)
                fillDrawable = requireContext().getDrawable(R.drawable.aibk_bg_linechart)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            val dataSetPersonal2nd = LineDataSet(personal2nd, "personal")
            dataSetPersonal2nd.apply {
                color = Color.parseColor("#ffc49d")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                setDrawFilled(true)
                fillDrawable = requireContext().getDrawable(R.drawable.aibk_bg_linechart2)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            val dataSetPersonal3rd = LineDataSet(personal3rd, "personal")
            dataSetPersonal3rd.apply {
                color = Color.parseColor("#ff8888")
                lineWidth = 1f
                setDrawCircleHole(false)
                setDrawCircles(false)
                setDrawFilled(true)
                fillDrawable = requireContext().getDrawable(R.drawable.aibk_bg_linechart3)
                mode = LineDataSet.Mode.CUBIC_BEZIER
            }
            lineChartData = LineData(dataSetPersonal, dataSetPersonal2nd, dataSetPersonal3rd)
            lineChartData.setDrawValues(false)
            this.data = lineChartData
            axisLeft.apply {
                setDrawGridLines(false)
                textSize = 9f
                textColor = Color.parseColor("#999999")
                setExtraOffsets(5f, 0f, 0f, 0f)
                spaceBottom = 0f
                granularity = 0.1f
                axisMinimum = 0f
                axisMaximum = 10.5f
                valueFormatter = IAxisValueFormatter { value, axis ->
                    when (value) {
                        0f -> "0"
                        data.Bad.toFloat() -> "${if (type == 0) "能朗读" else "能看懂"}${
                        BigDecimal(data.Bad).stripTrailingZeros()
                        }分"
                        data.Just.toFloat() -> "${if (type == 0) "能听懂" else "能拼写"}${
                        BigDecimal(data.Just).stripTrailingZeros()
                        }分"
                        data.Good.toFloat() -> "${if (type == 0) "能口语表达" else "能书面表达"}${
                        BigDecimal(data.Good).stripTrailingZeros()
                        }分"
                        10f -> "10"
                        else -> ""
                    }
                }
            }
            val trans = getTransformer(YAxis.AxisDependency.LEFT)
            rendererLeftYAxis = MyLineChartRender(viewPortHandler, axisLeft, trans)
            axisRight.isEnabled = false
            legend.isEnabled = false
            description.isEnabled = false
            setPinchZoom(false)
            setScaleEnabled(false)
            val markerView = MyMarkView(requireContext(), R.layout.item_achievement_markview)
            markerView.chartView = this
            marker = markerView
            xAxis.apply {
                position = XAxis.XAxisPosition.BOTTOM
                setDrawAxisLine(true)
                setDrawGridLines(false)
                setDrawLabels(false)
                extraBottomOffset = 10f
            }
            animateX(1000)
        }
    }

    inner class MyMarkView(context: Context, layoutResource: Int) :
            MarkerView(context, layoutResource) {
        override fun refreshContent(e: Entry?, highlight: Highlight?) {
            val position = e!!.x.toInt()
            val position2nd = position - platesDetail!!.CognitiveList.FirstList.size
            val position3rd = position - platesDetail!!.CognitiveList.FirstList.size - platesDetail!!.CognitiveList.SecondList.size
            val cogntiveList = platesDetail!!.CognitiveList.FirstList
            val cogntiveList2nd = platesDetail!!.CognitiveList.SecondList
            val cogntiveList3rd = platesDetail!!.CognitiveList.ThirdList
            tv_hint.text = when {
                position <= cogntiveList.size - 1 -> "${cogntiveList[position].ZsdString}\n${if (tv_excellent.tag == 1) "个人认知积分：" + cogntiveList[position].PersonalScore.toString() + "\n优秀学生认知积分：" + cogntiveList[position].ExcellentScore.toString() else "个人认知积分：" + cogntiveList[position].PersonalScore.toString()}"
                position <= cogntiveList.size + cogntiveList2nd.size - 1 -> "${cogntiveList2nd[position2nd].ZsdString}\n${if (tv_excellent.tag == 1) "个人认知积分：" + cogntiveList2nd[position2nd].PersonalScore.toString() + "\n优秀学生认知积分：" + cogntiveList2nd[position2nd].ExcellentScore.toString() else "个人认知积分：" + cogntiveList2nd[position2nd].PersonalScore.toString()}"
                else -> "${cogntiveList3rd[position3rd].ZsdString}\n${if (tv_excellent.tag == 1) "个人认知积分：" + cogntiveList3rd[position3rd].PersonalScore.toString() + "\n优秀学生认知积分：" + cogntiveList3rd[position3rd].ExcellentScore.toString() else "个人认知积分：" + cogntiveList3rd[position3rd].PersonalScore.toString()}"
            }
            super.refreshContent(e, highlight)
        }
    }
}